import { useEffect, useCallback, useRef } from 'react';

interface UseAutoSaveOptions {
  key: string;
  delay?: number; // 延迟时间（毫秒），默认30秒
  enabled?: boolean; // 是否启用自动保存
}

/**
 * 自动保存Hook
 * 在内容变化后延迟保存到localStorage
 * 组件卸载时立即保存
 */
export function useAutoSave(
  content: string,
  options: UseAutoSaveOptions
) {
  const { key, delay = 30000, enabled = true } = options;
  const timerRef = useRef<NodeJS.Timeout>();
  const lastSavedRef = useRef<string>('');

  // 保存到localStorage
  const save = useCallback(() => {
    if (!enabled || !content) return;

    try {
      localStorage.setItem(key, content);
      lastSavedRef.current = content;
      console.log(`[AutoSave] Saved to ${key}`);
    } catch (error) {
      console.error('[AutoSave] Failed to save:', error);
    }
  }, [content, key, enabled]);

  // 延迟保存
  const debouncedSave = useCallback(() => {
    if (!enabled) return;

    // 清除之前的定时器
    if (timerRef.current) {
      clearTimeout(timerRef.current);
    }

    // 设置新的定时器
    timerRef.current = setTimeout(() => {
      // 只在内容实际变化时保存
      if (content !== lastSavedRef.current) {
        save();
      }
    }, delay);
  }, [content, delay, enabled, save]);

  // 内容变化时触发延迟保存
  useEffect(() => {
    if (content) {
      debouncedSave();
    }

    // 清理函数
    return () => {
      if (timerRef.current) {
        clearTimeout(timerRef.current);
      }
    };
  }, [content, debouncedSave]);

  // 组件卸载时立即保存
  useEffect(() => {
    return () => {
      if (content && content !== lastSavedRef.current && enabled) {
        try {
          localStorage.setItem(key, content);
          console.log(`[AutoSave] Saved on unmount to ${key}`);
        } catch (error) {
          console.error('[AutoSave] Failed to save on unmount:', error);
        }
      }
    };
  }, [content, key, enabled]);

  // 恢复草稿
  const restoreDraft = useCallback(() => {
    if (!enabled) return null;

    try {
      const draft = localStorage.getItem(key);
      if (draft) {
        console.log(`[AutoSave] Restored draft from ${key}`);
        lastSavedRef.current = draft;
      }
      return draft;
    } catch (error) {
      console.error('[AutoSave] Failed to restore draft:', error);
      return null;
    }
  }, [key, enabled]);

  // 清除草稿
  const clearDraft = useCallback(() => {
    if (!enabled) return;

    try {
      localStorage.removeItem(key);
      lastSavedRef.current = '';
      console.log(`[AutoSave] Cleared draft from ${key}`);
    } catch (error) {
      console.error('[AutoSave] Failed to clear draft:', error);
    }
  }, [key, enabled]);

  // 手动保存
  const manualSave = useCallback(() => {
    if (timerRef.current) {
      clearTimeout(timerRef.current);
    }
    save();
  }, [save]);

  return {
    restoreDraft,
    clearDraft,
    manualSave,
  };
}
